package me.work.pay.jsyl.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;
import com.yzy.voice.ReturnPayResult;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.work.pay.jsyl.app.Constants;
import me.work.pay.jsyl.app.MD5Utils;
import me.work.pay.jsyl.app.utils.RxUtil;
import me.work.pay.jsyl.mvp.contract.PayContract;
import me.work.pay.jsyl.mvp.model.entity.PayData;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 09/12/2020 16:02
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class PayPresenter extends BasePresenter<PayContract.Model, PayContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public PayPresenter(PayContract.Model model, PayContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public String getRandomNickname(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    /**
     * 获得收款二维码
     *
     * @param val 支付金额
     */
    public void load_pay(String val) {
//        SPUtils.getInstance().put(Constants.sp_shop_id, "7898ffe6550cc695ce6d31c248ced1a6");

        Map<String, Object> map = new HashMap<>();
        String shop_id = SPUtils.getInstance().getString(Constants.sp_shop_id);
        String shop_name = SPUtils.getInstance().getString(Constants.sp_shop_name);
        String sn = Constants.sn;
        String order_id = "201200551515121321331";//arf_a8_时间20位+10位随机数
        map.put("shop_id", shop_id);
        long currentTime = System.currentTimeMillis();
        String timeNow = new SimpleDateFormat("yyyyMMddHHmmss").format(currentTime);
        order_id = "arf_a8_" + timeNow + getRandomNickname(10);
        map.put("order_id", order_id);
        map.put("money", val);
        map.put("version", "3.0");
        map.put("notify_url", "http://www.congmingpay.com");
        map.put("device", sn);
        map.put("terminal_id", sn);
//        String stringA = "shop_id=" + shop_id + "&order_id=" + order_id + "&money=" + val + "&version=3.0&notify_url=http://www.congmingpay.com" +
//                "&device=" + shop_name + "&terminal_id=" + sn;
        String stringA = "device=" + sn + "&money=" + val + "&notify_url=http://www.congmingpay.com" + "&order_id=" + order_id +
                "&shop_id=" + shop_id + "&terminal_id=" + sn + "&version=3.0";
        stringA += "&key=" + SPUtils.getInstance().getString(Constants.APIKEY);
        map.put("sign", MD5Utils.stringToMD5(stringA).toUpperCase());
        /**
         * shop_id ：商户号
         * 		order_id ：请求订单号
         * 		money ：金额，保留2位小数，单位元
         * 		version ： 固定值3.0
         * 		notify_url ： 回调地址，如：http://www.congmingpay.com ，尽量不带参数
         * 		device ： 分店名称
         * 		terminal_id ： 设备id
         * 		terminal_source ： 设备品牌来源，请使用拼音缩写，如：银豹：yinbao；鑫奥康：xinaokang等
         * 		notify_num ： 回调次数，默认1次，最多5次
         * 		profit_share_type ： 分账类型
         * 		profit_share_info ： 分账详情
         * 		body ： 商品名称
         * 		goods_tag ： 商品或订单标示
         * 		detail ： 商品小票明细
         * 		sign ： 签名
         * */
        mModel.load_pay(map)
                .compose(RxUtil.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<PayData>(mErrorHandler) {
                    @Override
                    public void onNext(PayData data) {
                        EventBus.getDefault().post(new ReturnPayResult(3,new Gson().toJson(data)));
                        if (data.result_code.equals("fail")) {
                            ToastUtils.showShort(data.error_msg);
                            return;
                        }
                        mRootView.load_pay(data);
                    }

                    @Override
                    public void onError(Throwable t) {
                        String a = "";
                    }
                });
    }
}
